package com.chocus.core.service.solr;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chocus.core.bean.product.Product;
import com.chocus.core.bean.product.ProductQuery;
import com.chocus.core.bean.product.Sku;
import com.chocus.core.bean.product.SkuQuery;
import com.chocus.core.dao.product.ProductDao;
import com.chocus.core.dao.product.SkuDao;

import cn.itcast.common.page.Pagination;

@Service("solrService")
public class SolrServiceImpl implements SolrService {

	@Autowired
	private SolrServer solrServer;

	@Autowired
	private ProductDao productDao;
	@Autowired
	private SkuDao skuDao;

	/**
	 * 保存商品到solr
	 * 
	 * @param id
	 */
	public void saveProductToSolr(Long id) {
		// 发送数据到solr
		SolrInputDocument doc = new SolrInputDocument();
		Product p = productDao.selectByPrimaryKey(id);
		// id
		doc.setField("id", id);
		// name
		doc.setField("name_ik", p.getName());
		// url
		doc.setField("url", p.getImages() == null ? "" : p.getImages()[0]);
		// brandId
		doc.setField("brandId", p.getBrandId());
		// price select price from bbs_sku where product_id = 10002 order by
		// price asc limit 0,1
		SkuQuery skuQuery = new SkuQuery();
		skuQuery.setFields("price");
		skuQuery.createCriteria().andProductIdEqualTo(id);
		skuQuery.setOrderByClause(" price asc ");
		skuQuery.setPageNo(1);
		skuQuery.setPageSize(1);
		List<Sku> skuList = skuDao.selectByExample(skuQuery);
		doc.setField("price", skuList.get(0).getPrice());
		try {
			solrServer.add(doc);
			solrServer.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * sorl查询数据
	 * 
	 * @param keyWord
	 * @param pageNo
	 * @return
	 */
	public Pagination getPaginationBySolr(String keyWord, Integer pageNo, Long brandId, String price) {

		// 处理分页参数
		ProductQuery productQuery = new ProductQuery();
		productQuery.setPageNo(Pagination.cpn(pageNo));
		productQuery.setPageSize(8);
		// 构建结果集存放结果
		List<Product> products = new ArrayList<Product>();

		SolrQuery param = new SolrQuery();
		// sorl分页
		param.setStart(productQuery.getStartRow());
		param.setRows(productQuery.getPageSize());
		// 排序
		param.addSort("price", ORDER.asc);
		// 高亮
		// 设置高亮开关
		param.setHighlight(true);
		// 设置高亮的字段
		param.addHighlightField("name_ik");
		// 设置高亮的简单的样式
		param.setHighlightSimplePre("<span style='color:red;'>");
		param.setHighlightSimplePost("</span>");
		param.setHighlightFragsize(20);
		// 分页参数
		StringBuilder params = new StringBuilder();
		if (keyWord != null && !"".equals(keyWord.trim())) {
			// 设置查询参数
			param.set("q", "name_ik:" + keyWord);
			params.append("keyWord=").append(keyWord);
		}
		// 过滤条件
		if (price != null) {
			String[] prices = price.split("-");
			if (prices.length == 2) {
				Float startPrice = new Float(prices[0]);
				Float endPrice = new Float(prices[1]);
				param.addFilterQuery("price:[" + startPrice + " TO " + endPrice + "]");
			} else {
				Float startPrice = new Float(prices[0]);
				param.addFilterQuery("price:[" + startPrice + " TO *]");
			}
			params.append("&price=").append(price);
		}
		if (brandId != null) {
			// 品牌id
			param.addFilterQuery("brandId:" + brandId);
			params.append("&brandId=").append(brandId);
		}
		QueryResponse response = null;
		try {
			// 查询结果集
			response = solrServer.query(param);
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 取出结果集
		SolrDocumentList results = response.getResults();
		// 高亮专用，取高亮
		Map<String, Map<String, List<String>>> highLight = response.getHighlighting();
		// 遍历放入集合
		for (SolrDocument doc : results) {
			Product product = new Product();
			// id
			String id = (String) doc.get("id");
			product.setId(Long.parseLong(id));
			// name,设置高亮
			Map<String, List<String>> map = highLight.get(id);
			// String name = (String) doc.get("name_ik");
			List<String> list = map.get("name_ik");
			product.setName(list.get(0));
			// price
			product.setPrice((float) doc.get("price"));
			// brandId
			product.setBrandId(Long.parseLong(String.valueOf((int) doc.get("brandId"))));
			// url
			String url = (String) doc.get("url");
			product.setImgUrl(url);
			products.add(product);
		}
		// 分页
		Pagination pagination = new Pagination(productQuery.getPageNo(), productQuery.getPageSize(),
				(int) results.getNumFound());
		pagination.setList(products);
		String url = "/product/list";
		// 分页显示
		pagination.pageView(url, params.toString());

		return pagination;
	}

}
